//
//  SEGPublishTopicViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/6.
//

#import "SEGPublishTopicViewModel.h"
#import "SEGCommunitySocialManager.h"

@interface SEGPublishTopicViewModel ()

@property (nonatomic, strong) NSString *content;

@end

@implementation SEGPublishTopicViewModel {
    
}
- (instancetype)init {
    if (self = [super init]) {
        [self initData];
    }
    return self;
}

- (void)initData {
    self.photoMaxCount = 0;
}

- (RACSignal *)checkAndSendPublishRequestWithDesString:(NSString *)describeViewText {
    
    return [RACSignal concat:@[[self checkParamsSignalWithUploadString:describeViewText],[self sendRequest]]];
}


- (RACSignal *)checkParamsSignalWithUploadString:(NSString *)describeViewText {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        //去除前后空格加换行
        NSString *str = [describeViewText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        __block NSString *upLoadString = describeViewText;
        
        if (self.selectTopicModel.pgcType.intValue == 2) {
            //图文话题、需要判断是否上传图片
            if (self.savePicArray.count == 0) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请上传图片"}]];
                return nil;
            }
            
            if (upLoadString.length > 70) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"亲，您输入的内容已超过70字"}]];
                return nil;
            }
            
            if (str.length == 0) {
                upLoadString = @"";
            }
            
        }else if (self.selectTopicModel.pgcType.intValue == 1) {
            //文字话题
            if (str.length == 0) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"输入内容不能少于2个字"}]];
                return nil;
            }
            
            if (upLoadString.length < 2) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"输入内容不能少于2个字"}]];
                return nil;
            }
            if (upLoadString.length > 70) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"亲，您输入的内容已超过70字"}]];
                return nil;
            }
        }
        self.content = upLoadString;
        [subscriber sendNext:@(1)];
        //先清空数据
        [self.saveUrlArray removeAllObjects];
        if (self.savePicArray.count == 0) {
            //文字话题不需要图片
            [subscriber sendCompleted];
        }
        [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:self.savePicArray progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if(isSuccessed) {
                NSArray *data = result[@"data"];
                //存储图片链接
                [self.saveUrlArray removeAllObjects];
                [self.saveUrlArray addObjectsFromArray:data];
                [subscriber sendCompleted];
            }else {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"发布失败，请重试"}]];
            }
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)sendRequest {
    /// 请求发布
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        SEGProfileModel *sysAccount = [SEGProfileManager sharedManager].profile;
        NSString* nickName = sysAccount.nickname;
        if ([nickName length] == 0) {
            nickName = sysAccount.tel;
        }

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setValue:self.content forKey:@"quizContent"];
        NSString* urlString = [self.saveUrlArray componentsJoinedByString:@","];
        [dict setValue:urlString forKey:@"quizPic"];
        [dict setValue:[SEGProfileManager sharedManager].profile.jobCommunity forKey:@"communityId"];
        [dict setValue:@"5" forKey:@"objType"];
        [dict setValue:self.selectTopicModel.objId forKey:@"objId"];
        
        [dict setValue:kAccountUserID forKey:@"userId"];
        [dict setValue:self.selectTopicModel.quizTypeId forKey:@"quizTypeId"];
        [dict setValue:ValueToString(sysAccount.cityId) forKey:@"regionId"];
        [dict setValue:@"3" forKey:@"quizRangeId"];
        [dict setValue:ValueToString(sysAccount.jobCommunity) forKey:@"organId"];
        [dict setValue:self.selectTopicModel.title forKey:@"linkTitle"];
        
        [dict setValue:[NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName] forKey:@"communityName"];
        [dict setValue:self.selectTopicModel.objId forKey:@"linkUrl"];
        
        
        
        SEGCommunitySocialManager *manager = [[SEGCommunitySocialManager alloc] init];
        
        [manager requestSaveQuizWithParams:dict Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                //话题发帖积分行为设置
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.topic module:SEGIntegralModule.neighborhoodCircle businessID:self.selectTopicModel.objId finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                }];
                // 刷新话题列表
                [[NSNotificationCenter defaultCenter] postNotificationName:SEGAttendTopicFinishedNotification object:nil];
                
                [subscriber sendCompleted];
            }else {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
        }];
        
        return nil;
    }];
    return signal;
        
        
    

}


- (NSMutableArray *)savePicArray {
    if (!_savePicArray) {
        _savePicArray = [NSMutableArray array];
    }
    return _savePicArray;
}

- (NSMutableArray *)saveUrlArray {
    if (!_saveUrlArray) {
        _saveUrlArray = [NSMutableArray array];
    }
    return _saveUrlArray;
}

- (void)setSelectTopicModel:(SEGTopicDataItemModel *)selectTopicModel {
    if ([_selectTopicModel.objId isEqualToString:selectTopicModel.objId]) {
        return;
    }
    
    _selectTopicModel = selectTopicModel;
    self.photoMaxCount = (selectTopicModel.pgcType.intValue == 1?0:9);
    [self.savePicArray removeAllObjects];
    [self.saveUrlArray removeAllObjects];
    
}


@end
